package happy.diandiankong.api.client;

import com.alibaba.fastjson.JSONObject;
import happy.diandiankong.api.exception.ApiServerException;
import happy.diandiankong.api.model.GpioInput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Title.
 * <p>
 * Description.
 *
 * @author Bill Lv {@literal <billcc.lv@hotmail.com>}
 * @version 1.0
 * @since 2016-10-30
 */
public class ApiClient extends CommonClient {
    static final Logger LOGGER = LoggerFactory.getLogger(ApiClient.class);

    static class ApiClientHolder {
        static final ApiClient INSTANCE = new ApiClient();
    }

    public static ApiClient getInstance() {
        return ApiClientHolder.INSTANCE;
    }

    private ApiClient() {

    }

    @Override
    protected Map<String, String> getAuthHeaders() {
        final Map<String, String> params = new HashMap<>();
        params.put("Authorization", "Basic YWRtaW46MTIzNDU2Nzg5YWJj");
        params.put("Origin", "http://unios.cc");
        params.put("Accept-Encoding", "gzip, deflate");
        params.put("Accept-Language", "en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4");
        params.put("X-Sitewhere-Tenant", "sitewhere1234567890");
        params.put("Cookie", "JSESSIONID=B52828ACD5955F429C9E7E3EA4944559; i18next=zh");
        params.put("Connection", "keep-alive");
        params.put("DNT", "1");
        return params;
    }

    public int postGpio(GpioInput gpioInput) throws IOException, ApiServerException {
        final String input = JSONObject.toJSONString(gpioInput);
        LOGGER.info("input: {}", input);
        final String resp = post("http://unios.cc/console/api/assignments/99d80b1f-6d96-4592-97ea-c34ff13723a0/invocations", input);
        final JSONObject jsonObject = JSONObject.parseObject(resp);
        final JSONObject parameterValues = jsonObject.getJSONObject("parameterValues");
        final Integer act = parameterValues.getInteger("act");
        return act;
    }
}
